package br.net.woodstock.tickettoride.client.config;

import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.Certificate;

import br.net.woodstock.rockframework.security.store.KeyStoreType;

class PKCS12Reader {

	private static final KeyStoreType	KEYSTORE_TYPE	= KeyStoreType.PKCS12;

	public PKCS12 read(final String alias, final String storePassword, final String keyPassword, final InputStream inputStream) throws GeneralSecurityException, IOException {
		KeyStore keyStore = KeyStore.getInstance(PKCS12Reader.KEYSTORE_TYPE.getType());
		keyStore.load(inputStream, storePassword.toCharArray());
		PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, keyPassword.toCharArray());
		Certificate[] chain = keyStore.getCertificateChain(alias);
		return new PKCS12(privateKey, chain[0]);
	}
}
